package com.rmb.util;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Mr.Fu
 * @date 2021/1/12 19:10
 */
public class CreateFileUtil {

    static String s = Thread.currentThread().getContextClassLoader().getResource("com/rmb/entity/files").toString();

    static String replace = s.replace("file:/", "");

    private static File getFile(String classFuncName) throws IOException {
        File htmlFile = new File(replace + "/" + classFuncName + ".java");

        if(!htmlFile.exists()) {
            try {
                //创建该文件
                htmlFile.createNewFile();

            }catch(IOException e){
                e.printStackTrace();
            }
        }else {
            //删除该文件
            htmlFile.delete();
        }

        //创建缓冲输入流，将文件放到缓冲区里
        return htmlFile;
    }

    private static BufferedWriter getBw(File file) throws IOException {
        return new BufferedWriter(new FileWriter(file));
    }

    /**
     * 编译代码
     * @param classFuncName
     * @return
     * @throws IOException
     */
    public static String createFileUtil(String classFuncName) throws IOException {

        //定义模板
        String str= "import java.util.Map;\n" +
                "public class aaa{\n" +
                "\tpublic void execute(Map<String, Object> params){\n" +
                "\t\tSystem.out.println(\"3组最牛逼\");\n" +
                "\t}\n" +
                "}";

        File htmlFile = getFile(classFuncName);

        try (BufferedWriter bw = getBw(htmlFile)) {

            bw.write(str);
            bw.flush();

        } finally { //后置处理代码，无论异常是否被捕获，finally的代码一定会被执行。
            //自定义类加载器并编译java源文件
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            String s1 = htmlFile.toString();
            int result = compiler.run(null, null, null, s1);
            System.out.println(result == 0 ? "编译成功" : "编译失败");
        }
        return str;

    }


    public static String updateFileUtil(String classFuncName,String fileContent) throws IOException {

        //创建缓冲输入流，将文件放到缓冲区里
        File htmlFile = getFile(classFuncName);

        try (BufferedWriter bw = getBw(htmlFile)) {
            bw.write(fileContent);
            bw.flush();
        } finally { //后置处理代码，无论异常是否被捕获，finally的代码一定会被执行。
            //自定义类加载器并编译java源文件
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            String s1 = htmlFile.toString();
            int result = compiler.run(null, null, null, s1);
            System.out.println(result == 0 ? "编译成功" : "编译失败");
            URL[] urls = new URL[]{new URL("file:/" + replace + "/")};
            URLClassLoader loader = new URLClassLoader(urls);
            try {
                Class c = loader.loadClass(classFuncName);
                Map<String, Object> stringObjectConcurrentHashMap = new ConcurrentHashMap<>(16);
                c.getMethod("execute", Map.class).invoke(c.newInstance(),stringObjectConcurrentHashMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileContent;

    }

    public static void main(String[] args) throws IOException {
        String aaa = createFileUtil("aaa");
        System.out.println(aaa);
        System.out.println("3组最牛逼");
    }


}
